package tictactoe.Display;

import tictactoe.Service.Application;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created with IntelliJ IDEA.
 * User: gmatt
 * Date: 24.11.2012
 * Time: 17:08
 */
public class Display extends JFrame implements ActionListener{

    private JButton[] buttons;

    private Application app;

    public void setApp(Application app) {
        this.app = app;
    }
    public Display() {
        super("TicTacToe");
        this.setSize(300, 300);
        buttons = new JButton[9];
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
        this.setLayout(new GridLayout(3, 3));
        for ( int i = 0; i < 9; i++ ) {
            buttons[i] = new JButton("");
            this.add(buttons[i]);
            buttons[i].addActionListener(this);
            buttons[i].setName(String.valueOf(i));
        }
        this.setVisible(true);
    }

    public void showResult(int index, String value) {
        buttons[index].setText(value);
        buttons[index].setEnabled(false);
    }

    public JButton[] getButtons() {
        return buttons;
    }

    public void winResult(String winner) {
        if (winner != null)
            JOptionPane.showMessageDialog(this, "Player " + winner + " wins!");
        else
            JOptionPane.showMessageDialog(this, "Tie!");
        this.dispose();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton pressed = (JButton)e.getSource();
        int index = Integer.valueOf(pressed.getName());
        app.changeState(index);
    }
}
